package com.oss.service.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oss.entity.system.Token;
import com.oss.enums.IsDeletedEnum;
import com.oss.mapper.system.TokenMapper;
import com.oss.util.IPUtils;
import com.oss.util.SnowFlakeUtil;
import com.oss.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author chengqiang
 */
@Service
public class TokenService extends ServiceImpl<TokenMapper, Token> {
    @Autowired
    TokenMapper tokenMapper;
    @Autowired
    TimeUtil timeUtil;
    @Autowired
    HttpServletRequest request;

    /**
     * 插入一条登录的token
     * 每一次登录都生成token, 既可以存储token, 又可以做登录日志使用
     *  1. 有  直接返回有效token
     *  2. 无  新插入一条token
     * @param userId 用户ID
     * @param token  token
     */
    public void insertToken(String userId ,String token){
        Token tokenEntity = new Token();
        tokenEntity.setTokenId(SnowFlakeUtil.getID());
        tokenEntity.setUserId(userId);
        tokenEntity.setExpirationTime(timeUtil.getExpirationTime());
        tokenEntity.setToken(token);
        String ip = IPUtils.getIpAdrress(request);
        tokenEntity.setIp(ip);
        tokenMapper.insert(tokenEntity);
    }

    /**
     * 根据用户ID获取token
     * 获取用户最后一条token
     * @param token token
     * @return 返回token对象
     */
    public Token getTokenByTokenAndUserID(String token){
        LambdaQueryWrapper<Token> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Token::getToken,token);
        lambdaQueryWrapper.eq(Token::getIsDeleted, IsDeletedEnum.NO);
        //lambdaQueryWrapper.ge(TB_Token::getExpirationTime, LocalDateTime.now());
        lambdaQueryWrapper.orderByDesc(Token::getExpirationTime);
        List<Token> list =  tokenMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }
}
